<?php

class LoginController extends Front_Libraries_Controller_Public
{

    public function indexAction()
    {
//        if(Zend_Auth::getInstance()->hasIdentity())
//        {
//            $this->_redirect('/front/index');
//        }
        
        $request = $this->_request;
        
        $loginForm = new Front_Form_Login();
        $loginForm->setAction('/front/login');
        
        $errorMessage = "";
        $message = $request->getParam('message');
        
        if($request->isPost())  
        {
            if($loginForm->isValid($request->getPost()))  
            {
                // get the username and password from the form  
                $username = $loginForm->getValue('username');  
                $password = $loginForm->getValue('password');  

                $dmdAdapter = new Front_Libraries_Auth_DMDAuthAdapter($username, $password);

                $auth = Zend_Auth::getInstance();  
                $result = $auth->authenticate($dmdAdapter);
                // is the user a valid one?  
                if($result->isValid())  
                {  
                    // get all info about this user from the login table  
                    // ommit only the password, we don't need that  
                    $userInfo = $dmdAdapter->getResultObject();  

                    // the default storage is a session with namespace Zend_Auth  
                    $authStorage = $auth->getStorage();  
                    $authStorage->write($userInfo);  

                    $this->_redirect('backend');  
                } 
                else  
                {  
                    $errorMessage = "Wrong username or password provided. Please try again.";  
                }  
            }  
        }
        
        $this->view->message = $message;
        $this->view->errorMessage = $errorMessage;
        $this->view->loginForm = $loginForm; 
    
        
    }

    public function logoutAction()  
    {  
        // clear everything - session is cleared also!
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('front/login/index');
    }
    
}
